package com.xpffly.springboot.config.db.druid;

import com.xpffly.springboot.config.db.druid.annotation.DataSourceNames;

import com.xpffly.springboot.config.db.druid.annotation.MyDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: xpengfei
 * @Date: 2020/12/9 22:11
 * @Description：多数据源切面处理
 */
@Aspect
@Component
@Order(value = -100)
public class DruidDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DruidDataSourceAspect.class);

    @Pointcut("@annotation(com.xpffly.springboot.config.db.druid.annotation.MyDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MyDataSource myDataSource = method.getAnnotation(MyDataSource.class);

        if (myDataSource == null) {
            DruidDynamicDataSource.set(DataSourceNames.STOCK_DB);
            logger.info("set mysql stock");
        } else {
            DruidDynamicDataSource.set(myDataSource.name());
            logger.info("set" + myDataSource.name());
        }
        try {
            return point.proceed();
        } finally {
            DruidDynamicDataSource.clear();
            logger.info("clear datasource");
        }
    }


}
